#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  main_exec.py
#       Author @  Huoty
#  Create date @  2016-07-26 15:15:00
#  Description @
# *************************************************************

from __future__ import print_function

import sys
import imp
from pprint import pprint

class Context(object):
    pass

class PersistentState(object):
    pass


# Script starts from here

if __name__ == "__main__":
    outer_code_moudle = imp.new_module('outer_code')
    outer_code_moudle.__file__ = 'outer_code.py'
    sys.modules["outer_code"] = outer_code_moudle
    outer_code_scope = code_scope = outer_code_moudle.__dict__

    head_code = "import numpy as np\nfrom main_exec import PersistentState\ng=PersistentState()"
    exec(head_code, code_scope)
    origin_global_names = set(code_scope.keys())

    with open("outer_code.py", "rb") as f:
        outer_code = f.read()

    import __future__
    code_obj = compile(outer_code, "outer_code.py", "exec", flags=__future__.unicode_literals.compiler_flag)
    exec(code_obj, code_scope)
    # 去除掉内建名字空间的属性，仅保留外部代码中添加的属性
    outer_code_global_names = set(outer_code_scope.keys()) - origin_global_names

    outer_func_initialize = code_scope.get("initialize", None)
    outer_func_handle_data = code_scope.get("handle_data", None)

    context = Context()
    context.y = 999
    outer_func_initialize(context)
    outer_scope_g = outer_code_scope["g"]
    setattr(outer_scope_g, u'x', u"xxx")
    setattr(outer_scope_g, u'y', u"yyy")
    outer_func_handle_data(context, None)

    g = outer_code_scope["g"]
    assert g.c == 2886
    print("g.c: %s" % g.c)
    print(dir(g))
    print(dir(context))
    pprint(outer_code_moudle.__dict__)

